#include "TcpServer.hpp"
#include "HttpProtocol.hpp"
#include <iostream>
#include <string>
#include <functional>


std::string HandlerHttpRequest(std::string& request)
{
    HttpRequest req(request);
    req.print();
    std::string http_content;
    req.getFileContent(&http_content);

    int http_code = 200;
    if(http_content.empty())
    {
        http_code = 404;
        HttpRequest::_getFileContentHelper("/404.html", &http_content);
    }

    HttpResponse resp;
    std::string http_code_desc = HttpResponse::codeDesc(http_code);
    std::string http_version = "HTTP/1.1";
    resp.setStatuLine(http_version, http_code, http_code_desc);

    std::string http_header = "Content-Length: " + std::to_string(http_content.size()) + "\r\n";
    resp.addHeader(http_header);
    std::string namecookie = "Set-Cookie: username=zhangsan\r\n";
    resp.addHeader(namecookie);

    resp.setContent(http_code_desc);
    cout << "******************************************" << endl;
    resp.print();
    cout << "******************************************" << endl;

    std::string response = resp.serialize();
    return response;
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        cout << "Usage: " << argv[0] << " port" << endl;
        return 1;
    }

    uint16_t port = atoi(argv[1]);

    auto handler_lambda = [](std::shared_ptr<Socket> client_socket) -> std::string {
        std::string data;
        bool ret = client_socket->Recv(&data, 1024);
        if(ret)
        {
            std::string resp = HandlerHttpRequest(data);
            data = resp;
        }
        return data;
    };
    auto handler_request = std::bind(handler_lambda, std::placeholders::_1);

    TcpServer server(port, handler_request);
    server.Loop();

    return 0;
}